<template>
  <div class="h-full flex flex-col p-4">
    <!-- 报表容器 -->
    <div class="flex-1 flex flex-col bg-white rounded-lg shadow min-h-0">
      <!-- 筛选区域 -->
      <div class="p-6 pb-0">
        <div class="flex items-center justify-between mb-6">
          <div class="flex items-center gap-4">
            <!-- 时间类型选择器 -->
            <ToggleGroup v-model="activeTimeType" :options="timeTypeOptions" @change="setActiveTimeType" />

            <!-- 日期范围选择器 -->
            <div class="flex items-center gap-2">
              <el-date-picker v-model="startDate" :type="datePickerType" :placeholder="getStartPlaceholder()"
                :format="dateFormat" class="w-40" />
              <span class="text-gray-500">→</span>
              <el-date-picker v-model="endDate" :type="datePickerType" :placeholder="getEndPlaceholder()"
                :format="dateFormat" class="w-40" />
            </div>
          </div>

          <!-- 导出按钮 -->
          <el-button type="primary" @click="handleExport" class="export-button">
            Export
          </el-button>
        </div>
      </div>

      <!-- 表格部分，统一状态展示 -->
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="displayedReportData.length > 0"
        @retry="reload"
      >
        <ReportTable
          :report-data="displayedReportData"
          :pagination="pagination"
          @page-change="handleCurrentChange"
          @size-change="handleSizeChange"
          class="flex-1 px-6"
        />
      </PageState>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import ReportTable from "./components/ReportTable.vue";
import PageState from "@/components/base/PageState.vue";
import ToggleGroup from "@/components/ToggleGroup/index.vue";

// 定义报表数据类型
interface ReportItem {
  id: string;
  date: string;
  solarProduction: number;
  homeConsumption: number;
  batteryCharge: number;
  batteryDischarge: number;
  exportToGrid: number;
  importFromGrid: number;
}

// 模拟报表数据
const mockReportData: ReportItem[] = [
  {
    id: "1",
    date: "2025-03-12",
    solarProduction: 1112.3,
    homeConsumption: 1112.3,
    batteryCharge: 1112.3,
    batteryDischarge: 1112.3,
    exportToGrid: 1112.3,
    importFromGrid: 1112.3
  },
  {
    id: "2",
    date: "2025-03-11",
    solarProduction: 1050.75,
    homeConsumption: 980.25,
    batteryCharge: 850.6,
    batteryDischarge: 920.45,
    exportToGrid: 890.3,
    importFromGrid: 750.85
  },
  {
    id: "3",
    date: "2025-03-10",
    solarProduction: 1320.45,
    homeConsumption: 1180.9,
    batteryCharge: 1050.3,
    batteryDischarge: 1100.75,
    exportToGrid: 1200.5,
    importFromGrid: 680.25
  },
  // 重复数据以测试分页
  ...Array.from({ length: 82 }, (_, index) => ({
    id: `${index + 4}`,
    date: `2025-03-${String(9 - (index % 9)).padStart(2, "0")}`,
    solarProduction: 1112.3 + Math.random() * 200 - 100,
    homeConsumption: 1112.3 + Math.random() * 200 - 100,
    batteryCharge: 1112.3 + Math.random() * 200 - 100,
    batteryDischarge: 1112.3 + Math.random() * 200 - 100,
    exportToGrid: 1112.3 + Math.random() * 200 - 100,
    importFromGrid: 1112.3 + Math.random() * 200 - 100
  }))
];

defineProps({
  systemId: {
    type: String,
    required: true
  }
});

// 时间类型选项
const timeTypeOptions = [
  { label: "Daily", value: "daily" },
  { label: "Monthly", value: "monthly" },
  { label: "Yearly", value: "yearly" }
];

// 当前选中的时间类型
const activeTimeType = ref("daily");

// 日期选择
const startDate = ref(new Date("2020-11-08"));
const endDate = ref(new Date("2020-12-23"));

// 根据时间类型计算日期选择器类型
const datePickerType = computed(() => {
  switch (activeTimeType.value) {
    case "monthly":
      return "month";
    case "yearly":
      return "year";
    default:
      return "date";
  }
});

// 根据时间类型计算日期格式
const dateFormat = computed(() => {
  switch (activeTimeType.value) {
    case "monthly":
      return "YYYY-MM";
    case "yearly":
      return "YYYY";
    default:
      return "YYYY-MM-DD";
  }
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 模拟报表数据
const allReportData = ref<ReportItem[]>([...mockReportData]);

// 过滤后的数据
const filteredReportData = computed(() => {
  // 这里可以根据日期范围和时间类型过滤数据
  return allReportData.value;
});

// 显示的数据（应用分页）
const displayedReportData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredReportData.value.slice(start, end);
});

// 监听过滤数据变化，更新总数
watch(
  filteredReportData,
  newFiltered => {
    pagination.total = newFiltered.length;
  },
  { immediate: true }
);

// 方法
const setActiveTimeType = (value: string) => {
  activeTimeType.value = value;
  // 重置日期
  if (value === "monthly") {
    startDate.value = new Date("2020-11");
    endDate.value = new Date("2020-12");
  } else if (value === "yearly") {
    startDate.value = new Date("2020");
    endDate.value = new Date("2023");
  } else {
    startDate.value = new Date("2020-11-08");
    endDate.value = new Date("2020-12-23");
  }
};

const getStartPlaceholder = () => {
  switch (activeTimeType.value) {
    case "monthly":
      return "2020-11";
    case "yearly":
      return "2020";
    default:
      return "2020-11-08";
  }
};

const getEndPlaceholder = () => {
  switch (activeTimeType.value) {
    case "monthly":
      return "2020-12";
    case "yearly":
      return "2023";
    default:
      return "2020-12-23";
  }
};

const handleExport = () => {
  console.log("Exporting data...");
  // 这里实现导出逻辑
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
};

onMounted(() => {
  // 初始化数据
});

// 统一状态
const loading = ref(false);
const errorMessage = ref("");
const reload = () => {
  errorMessage.value = "";
  // 若后续接入API，这里触发加载；目前为本地数据，直接重置分页
  pagination.currentPage = 1;
};
</script>

<style scoped lang="scss">
.export-button {
  background-color: #2d6962;
  border-color: #2d6962;

  &:hover {
    background-color: #1e4a44;
    border-color: #1e4a44;
  }
}

/* 确保页面撑满高度 */
.h-full {
  height: 100%;
}
</style>
